/**
 * @desc 版本管理，新增/修改弹框
 * @author yd_zhaorongjun
 */
<template>
  <div>
    <el-dialog
      :title="title"
      class="gl_dialog_TitleLine editVersion"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="660px"
    >
      <el-scrollbar v-loading="loading" wrap-class="scrollbar-wrapper gl_dialog_height fixHeight">
        <el-form ref="EditionCreateDto" class="gl_form_mini" :model="EditionCreateDto" :rules="EditionCreateDto_Rules" label-position="right" label-width="120px" style="padding-right: 20px;">
          <el-row>
            <el-col :span="24">
              <!-- 版本名称 -->
              <el-form-item :label="$t('tenant.versionName')" prop="displayName">
                <el-input v-model="EditionCreateDto.displayName" :placeholder="$t('tenant.placeholder_versionName')" name="displayName" type="text" size="mini" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <!-- 描述 -->
              <el-form-item :label="$t('tenant.description')">
                <el-input
                  v-model="EditionCreateDto.description"
                  type="textarea"
                  show-word-limit
                  maxlength="200"
                  :placeholder="$t('tenant.placeholder_description')"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <!-- 功能选择 -->
            <el-form-item label="分配权限">
              <div>
                <el-checkbox v-model="isCheckAllItems" @change="selectAllClassfiy">授予所有权限</el-checkbox>
              </div>
              <el-row class="treeBox">
                <el-col :span="7" class="authority-type">
                  <el-button v-for="(item, index) in toggleTypeList" :key="item.code" :type="checkedIndex === index ? 'primary' : 'default'" style="width: 100%" size="mini" @click="selectType(index)">
                    {{ item.displayName }}
                  </el-button>
                </el-col>
                <el-col :span="16" :offset="1" class="authority-type">
                  <div>
                    <el-checkbox v-model="isCheckAll" @change="handleCheckAllChange">全选</el-checkbox>
                  </div>
                  <el-scrollbar wrap-class="scrollbar-wrapper">
                    <el-tree
                      ref="tree"
                      v-model="EditionCreateDto.functions"
                      :data="treeData"
                      class="tree_scroll"
                      highlight-current
                      show-checkbox
                      node-key="name"
                      default-expand-all
                      :props="defaultProps"
                      @check-change="handleCheckChange"
                    />
                  </el-scrollbar>
                  <!-- 试用模式更多设置 -->
                  <!-- 暂时不使用，先隐藏 -->
                  <!-- <div style="text-align: right;">
                    <el-button type="text" @click="openInnerVisible">{{ $t('tenant.moreSettings') }}</el-button>
                  </div> -->
                </el-col>
              </el-row>
            </el-form-item>
          </el-row>
        </el-form>
      </el-scrollbar>
      <span slot="footer" class="dialog-footer">
        <!-- 取消 -->
        <el-button size="mini" @click="dialogVisible = false">{{ $t('button.cancel') }}</el-button>
        <!-- 保存 -->
        <el-button v-if="type == 'new'" type="primary" :loading="submitLoading" size="mini" @click="saveNew()">{{ $t('button.save') }}</el-button>
        <!-- 保存 -->
        <el-button v-else type="primary" :loading="submitLoading" size="mini" @click="saveEdit()">{{ $t('button.save') }}</el-button>
      </span>
    </el-dialog>
    <!-- 版本更多设置 -->
    <el-dialog
      width="880px"
      :title="$t('tenant.VersionMoreSettings')"
      :visible.sync="innerVisible"
      :before-close="innerVisibleClose"
      :close-on-click-modal="false"
      class="gl_dialog_TitleLine"
      append-to-body
    >
      <el-form ref="EditionCreateDto_inner" :model="EditionCreateDto_extendDto" label-position="right" label-width="140px" style="padding-right: 30px;">
        <div class="innerVisible_box">
          <!-- 免费使用时长 -->
          <el-row type="flex" justify="center">
            <el-col :span="20" class="gl_mb_15 innerVisible_title">
              {{ $t('tenant.freeUseTime') }}：
            </el-col>
          </el-row>
          <el-row type="flex" justify="center" align="middle">
            <el-col :span="10">
              <el-radio-group v-model="freeDays.type" @change="changeFreeTime">
                <el-radio label="0">1天</el-radio>
                <el-radio label="1">1月</el-radio>
                <el-radio label="unlimited">不限</el-radio>
                <el-radio label="free">自动设置</el-radio>
              </el-radio-group>
            </el-col>
            <el-col :span="10">
              <el-date-picker
                v-model="freeDay"
                type="daterange"
                :range-separator="$t('tenant.to')"
                :start-placeholder="$t('tenant.placeholder_Date')"
                :end-placeholder="$t('tenant.placeholder_Date')"
                :disabled="!freeDays.isEnabled"
                size="mini"
                value-format="yyyy-MM-dd"
                @change="timeChange"
              />
            </el-col>
          </el-row>
          <!-- 授权使用人数 -->
          <el-row type="flex" justify="center">
            <el-col :span="20" class="gl_mb_15 innerVisible_title">
              {{ $t('tenant.authorizedUsers') }}：
            </el-col>
          </el-row>
          <el-row type="flex" justify="center" align="middle">
            <el-col :span="10">
              <el-radio-group v-model="maxUsers.type" @change="changePeoples">
                <el-radio label="0">1人</el-radio>
                <el-radio label="1">10人</el-radio>
                <el-radio label="unlimited">不限</el-radio>
                <el-radio label="free">自动设置</el-radio>
              </el-radio-group>
            </el-col>
            <el-col :span="10">
              <!-- 请输入人数 -->
              <el-input-number v-model="EditionCreateDto_extendDto.maxUsers" :disabled="!maxUsers.isEnabled" style="width:110px" controls-position="right" :min="0" :max="100" size="mini" />
              <span style="display: inline;padding-left:10px">{{ $t('tenant.peoples') }}</span>
            </el-col>
          </el-row>
        </div>

        <div class="innerVisible_box gl_pt_20">
          <el-row type="flex" justify="center" align="middle">
            <el-col :span="10">
              <!-- 允许创建赛事数量 -->
              <el-row type="flex" justify="center">
                <el-col :span="20" class="gl_mb_15 innerVisible_title">
                  {{ $t('tenant.createGames') }}：
                </el-col>
              </el-row>
              <el-radio-group v-model="maxEvents.type" class="gl_mr_15" @change="changeGames">
                <el-radio label="unlimited">不限</el-radio>
                <el-radio label="free">自动设置</el-radio>
              </el-radio-group>
              <template>
                <!-- 请输入数量 -->
                <el-input-number v-model="EditionCreateDto_extendDto.maxEvents" :disabled="!maxEvents.isEnabled" style="width:110px" name="name" type="number" controls-position="right" :min="0" size="mini" />
                <span style="display: inline;padding-left:10px">{{ $t('tenant.ge') }}</span>
              </template>
            </el-col>
            <el-col :span="10">
              <!-- 允许发布培训数量 -->
              <el-row type="flex" justify="center">
                <el-col :span="20" class="gl_mb_15 innerVisible_title">
                  {{ $t('tenant.trains') }}：
                </el-col>
              </el-row>
              <el-radio-group v-model="maxTraining.type" class="gl_mr_15" @change="changeTrains">
                <el-radio label="unlimited">不限</el-radio>
                <el-radio label="free">自动设置</el-radio>
              </el-radio-group>
              <template>
                <!-- 请输入数量 -->
                <el-input-number v-model="EditionCreateDto_extendDto.maxTraining" :disabled="!maxTraining.isEnabled" style="width:110px" name="name" type="number" controls-position="right" :min="0" size="mini" />
                <span style="display: inline;padding-left:10px">{{ $t('tenant.ge') }}</span>
              </template>
            </el-col>
          </el-row>

          <el-row type="flex" justify="center" align="middle" class="gl_mt_30">
            <el-col :span="10">
              <!-- 允许设置课程数量 -->
              <el-row type="flex" justify="center">
                <el-col :span="20" class="gl_mb_15 innerVisible_title">
                  {{ $t('tenant.curriculum') }}：
                </el-col>
              </el-row>
              <el-radio-group v-model="maxCourses.type" class="gl_mr_15" @change="changeCurriculum">
                <el-radio label="unlimited">不限</el-radio>
                <el-radio label="free">自动设置</el-radio>
              </el-radio-group>
              <template>
                <!-- 请输入数量 -->
                <el-input-number v-model="EditionCreateDto_extendDto.maxCourses" :disabled="!maxCourses.isEnabled" style="width:110px" name="name" type="number" controls-position="right" :min="0" size="mini" />
                <span style="display: inline;padding-left:10px">{{ $t('tenant.ge') }}</span>
              </template>
            </el-col>
            <el-col :span="10">
              <!-- 允许上传资源数量 -->
              <el-row type="flex" justify="center">
                <el-col :span="20" class="gl_mb_15 innerVisible_title">
                  {{ $t('tenant.uploads') }}：
                </el-col>
              </el-row>
              <el-radio-group v-model="maxResources.type" class="gl_mr_15" @change="changeUploads">
                <el-radio label="unlimited">不限</el-radio>
                <el-radio label="free">自动设置</el-radio>
              </el-radio-group>
              <template>
                <!-- 请输入数量 -->
                <el-input-number v-model="EditionCreateDto_extendDto.maxResources" :disabled="!maxResources.isEnabled" style="width:110px" name="name" type="number" controls-position="right" :min="0" size="mini" />
                <span style="display: inline;padding-left:10px">{{ $t('tenant.ge') }}</span>
              </template>
            </el-col>
          </el-row>
        </div>
        <div class=" gl_pt_20">
          <!-- 是否允许支持APP -->
          <el-row type="flex" justify="center" align="middle">
            <el-col :span="20" class="gl_mb_15 innerVisible_title">
              {{ $t('tenant.isApp') }}：
            </el-col>
          </el-row>
          <el-row type="flex" justify="center" align="middle">
            <el-col :span="20">
              <el-radio-group v-model="EditionCreateDto_extendDto.isSupportApp" class="gl_mr_15">
                <!-- 是 -->
                <el-radio :label="true">{{ $t('tenant.yes') }}</el-radio>
                <!-- 否 -->
                <el-radio :label="false">{{ $t('tenant.no') }}</el-radio>
              </el-radio-group>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <!-- 确定 -->
        <el-button type="primary" size="mini" @click="innerVisibleSaveNew()">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { translateByCode } from '@/lib/getTransData';
import { EditionCreateDto_extendDto, FeaturesQO } from '@/lib/form/tenantManagement.js';
import { EditionCreateDto, EditionDto } from '@/lib/form/swaggerForm';
import { EditionCreateDto_Rules } from '@/lib/validate/tenantManagement/index.js';
import { api_GET_EditionsId } from '@/extend/api/swaggerApi/saas';
import { api_GET_Features } from '@/extend/api/swaggerApi/feature-management';
import { CopyData, FormatDate } from '@/lib';

export default {
  name: 'CustomerModal',
  data() {
    return {
      FeaturesQO: new FeaturesQO(),
      EditionCreateDto: new EditionCreateDto(),
      EditionCreateDto_extendDto: new EditionCreateDto_extendDto(),
      EditionCreateDto_Rules: new EditionCreateDto_Rules(),
      loading: false,
      submitLoading: false,
      title: '',
      dialogVisible: false,
      innerVisible: false, // 内部弹框
      type: '', // 弹框状态，是新增和是修改 new 是新增，edit是修改
      treeNodes: [], // 把所有的id放一个数组，判断全选的时候用
      isCheckAll: false, // 是否全选
      // isCheckAllItems: false, // 是否全选所有权限
      freeDay: [],
      freeDays: { // 选择框的判断属性
        type: 'unlimited',
        isEnabled: false
      },
      maxUsers: { // 选择框的判断属性
        type: '0',
        isEnabled: false
      },
      maxEvents: { // 选择框的判断属性
        type: 'unlimited',
        isEnabled: false
      },
      maxTraining: {
        type: 'unlimited',
        isEnabled: false
      },
      maxCourses: {
        type: 'unlimited',
        isEnabled: false
      },
      maxResources: {
        type: 'unlimited',
        isEnabled: false
      },
      treeData: [], // 当前树结构
      currentCheckedData: [], // 当前树已勾选的id
      allCheckedData: [], // 当前树已勾选的id
      hasChecked: false, // 用于判断是否有勾选全选，验证用
      checkedIndex: 0,
      currentDay: '', // 当前日期
      getTreeList: [], // 获取的树结构数据
      toggleTypeList: [], // 勾选框的树结构数据
      unToggleTypeList: [], // 非勾选框的树结构数据
      sendDefaultList: [], // 非勾选框的树结构数据
      defaultProps: {
        children: 'features',
        label: 'displayName'
      }
    };
  },
  computed: {
    // 全选功能
    isCheckAllItems: {
      get: function() {
        if (this.toggleTypeList && this.toggleTypeList.length > 0) {
          for (let i = 0; i < this.toggleTypeList.length; i += 1) {
            const checked = this.selectAllRecursion(this.toggleTypeList[i].features);
            if (checked === 'False') {
              // eslint-disable-next-line vue/no-side-effects-in-computed-properties
              this.hasChecked = false;
              return false;
            }
          }
          return true;
        }
        return false;
      },
      set: function(val) {
        return val;
      }
    }
  },
  watch: {
    dialogVisible(val) {
      if (!val) {
        this.$refs['EditionCreateDto'].resetFields();
        if (this.$refs['EditionCreateDto_extendDto']) {
          this.$refs['EditionCreateDto_extendDto'].resetFields();
        }
      } else {
        this.getRoleList();
      }
    }
  },
  methods: {
    // 根据用户id获取信息
    api_GET_EditionsId() {
      api_GET_EditionsId(this.editId).then(res => {
        // 使用通过id获取版本信息的DTO
        this.EditionCreateDto = new EditionDto();
        CopyData(res, this.EditionCreateDto);
        CopyData(res, this.EditionCreateDto_extendDto);
        this.setRadiosType();
        console.log(this.EditionCreateDto);
      })
        .catch(() => {
        });
    },
    // 获取树结构数据
    getRoleList() {
      const _this = this;
      this.FeaturesQO.providerKey = this.editId || '';
      api_GET_Features(this.FeaturesQO).then(res => {
        _this.getTreeList = res.groups;
        _this.processingTree();
      })
        .catch(() => {
        });
    },
    // 处理树结构数据
    processingTree() {
      const _this = this;
      this.sendDefaultList = [];
      _this.unToggleTypeList = []; // 非勾选框的树结构数据
      _this.toggleTypeList = [];// 勾选框的树结构数据
      this.getTreeList.filter(item => {
        if (item.features[0].valueType && item.features[0].valueType.name === 'ToggleStringValueType') {
          _this.toggleTypeList.push(item);
        } else {
          _this.unToggleTypeList.push(item);
          _this.processingDefaultList(_this.unToggleTypeList);
        }
      });
      console.log(_this.toggleTypeList);
      this.selectType(0);
    },
    // 处理非勾选框的树结构数据
    processingDefaultList(data) {
      // eslint-disable-next-line no-redeclare
      const objForm = {
        name: '',
        value: ''
      };
      for (let i = 0; i < data.length; i += 1) {
        const item = data[i];
        if (item.valueType) {
          objForm.name = item.name;
          objForm.value = item.value;
          this.sendDefaultList.push(objForm);
        }
        if (item.features && item.features.length > 0) {
          this.processingDefaultList(item.features);
        }
      }
    },
    open(row) {
      this.dialogVisible = true;
      this.loading = true;
      this.type = row ? 'edit' : 'new';
      this.editId = row ? row.id : '';
      // 修改版本/添加版本  zh
      this.title = row ? translateByCode('tenant.editVersion') : translateByCode('tenant.addVersion');
      if (this.editId) {
        this.api_GET_EditionsId();
      } else {
        this.EditionCreateDto = new EditionCreateDto();
        this.EditionCreateDto_extendDto = new EditionCreateDto_extendDto();
        this.EditionCreateDto.isSupportApp = true;
        this.setRadiosType();
      }
    },
    // 设置扩展功能里的按钮显示
    setRadiosType() {
      this.freeDays.isEnabled = false;
      this.maxUsers.isEnabled = false;
      this.maxEvents.isEnabled = false;
      this.maxTraining.isEnabled = false;
      this.maxCourses.isEnabled = false;
      this.maxResources.isEnabled = false;
      // 免费时长
      if (this.EditionCreateDto_extendDto.freeDays === 0) {
        this.freeDays.type = 'unlimited';
      } else if (this.EditionCreateDto_extendDto.freeDays === 1) {
        this.freeDays.type = '0';
      } else {
        this.freeDays.type = 'free';
        this.freeDays.isEnabled = true;
        if (this.EditionCreateDto.creationTime) {
          this.EditionCreateDto_extendDto.freeDays = this.EditionCreateDto.freeDays;
          // eslint-disable-next-line no-unused-vars
          let endDate = new Date(this.EditionCreateDto.creationTime);
          endDate = endDate.setDate(endDate.getDate() + this.EditionCreateDto.freeDays);
          endDate = FormatDate(endDate, 'yyyy-MM-dd HH:mm:ss');
          console.log(endDate);
          this.$set(this.freeDay, 0, FormatDate(this.EditionCreateDto.creationTime, 'yyyy-MM-dd HH:mm:ss'));
          this.$set(this.freeDay, 1, endDate);
        }
      }
      // 授权使用人数
      if (this.EditionCreateDto_extendDto.maxUsers === 0) {
        this.maxUsers.type = 'unlimited';
      } else if (this.EditionCreateDto_extendDto.maxUsers === 1) {
        this.maxUsers.type = '0';
      } else if (this.EditionCreateDto_extendDto.maxUsers === 10) {
        this.maxUsers.type = '1';
      } else {
        this.maxUsers.type = 'free';
        this.maxUsers.isEnabled = true;
      }
      // 允许创建赛事数量
      if (this.EditionCreateDto_extendDto.maxEvents === 0) {
        this.maxEvents.type = 'unlimited';
      } else {
        this.maxEvents.type = 'free';
        this.maxEvents.isEnabled = true;
      }
      // 允许发布培训数量
      if (this.EditionCreateDto_extendDto.maxTraining === 0) {
        this.maxTraining.type = 'unlimited';
      } else {
        this.maxTraining.type = 'free';
        this.maxTraining.isEnabled = true;
      }
      // 允许设置课程数量
      if (this.EditionCreateDto_extendDto.maxCourses === 0) {
        this.maxCourses.type = 'unlimited';
      } else {
        this.maxCourses.type = 'free';
        this.maxCourses.isEnabled = true;
      }
      // 允许上传资源数量
      if (this.EditionCreateDto_extendDto.maxResources === 0) {
        this.maxResources.type = 'unlimited';
      } else {
        this.maxResources.type = 'free';
        this.maxResources.isEnabled = true;
      }
    },
    // 按模块分组筛选
    selectType (index) {
      this.treeData = [];
      this.treeNodes = [];
      this.currentCheckedData = [];
      this.checkedIndex = index;
      this.treeData = this.toggleTypeList[index].features;
      this.setCheckedKeysById(this.treeData);
      // 设置默认勾选的值
      this.$refs.tree.setCheckedKeys(this.currentCheckedData);
      this.$nextTick(function() {
        // 判断是否全选
        // eslint-disable-next-line eqeqeq
        if (this.treeNodes && (this.currentCheckedData == this.treeNodes.sort().toString())) {
          this.isCheckAll = true;
        } else {
          this.isCheckAll = false;
        }
        this.loading = false;
      });
    },
    // 分组的递归函数：用于多层级嵌套的勾选框改值赋值
    setCheckedKeysById(data, val) {
      for (let i = 0; i < data.length; i += 1) {
        const item = data[i];
        this.treeNodes.push(item.name);
        if (item.value === 'True') {
          this.currentCheckedData.push(item.name);
        }
        if (item.features && item.features.length > 0) {
          this.setCheckedKeysById(item.features);
        }
      }
    },
    // 获取树形结构选中的数据
    handleCheckChange(data, isCheck) {
      this.$set(this.EditionCreateDto, 'functions', this.$refs.tree.getCheckedKeys());
      // 点击勾选框判断是否全选
      if (this.isCheckAll) {
        const hasData = this.EditionCreateDto.functions.filter(i => data.name.indexOf(i) >= 0);
        this.isCheckAll = hasData.length > 0;
      }
      // 判断已勾选是否是所有都选择，需要跟树结构的所有nodes比较
      // eslint-disable-next-line eqeqeq
      if (this.EditionCreateDto.functions.sort().toString() == this.treeNodes.sort().toString()) {
        this.isCheckAll = true;
      }
      this.$set(this.EditionCreateDto, 'functions', this.$refs.tree.getCheckedKeys());
      this.selectClassfiyRecursion(this.treeData, isCheck, data.name);
    },
    // 按分组全选所有
    selectAllClassfiy(val) {
      if (val) {
        for (let i = 0; i < this.toggleTypeList.length; i += 1) {
          this.selectClassfiyRecursion(this.toggleTypeList[i].features, val);
          this.isCheckAll = true;
          this.$refs.tree.setCheckedNodes(this.treeData);
        }
      } else {
        for (let i = 0; i < this.toggleTypeList.length; i += 1) {
          this.selectClassfiyRecursion(this.toggleTypeList[i].features, val);
          this.isCheckAll = false;
          this.$refs.tree.setCheckedKeys([]);
        }
      }
    },
    /**
     * @desc 分组的递归函数：用于多层级嵌套的勾选框改值赋值.
     * @param {array} data 基础对象
     * @param {boolean} val 设置checked是否勾选
     * @param {string} name 如有该属性，则只更改该name的checked值，没有则改变全部
     */
    selectClassfiyRecursion(data, val, name) {
      for (let i = 0; i < data.length; i += 1) {
        const item = data[i];
        if (name) {
          if (name === item.name) {
            this.$set(item, 'value', val ? 'True' : 'False');
            break;
          }
        } else {
          this.$set(item, 'value', val ? 'True' : 'False');
        }
        if (item.features && item.features.length > 0) {
          this.selectClassfiyRecursion(item.features, val, name);
        }
      }
    },
    // 当前树形结构的全选控制
    handleCheckAllChange() {
      if (this.isCheckAll) {
        this.selectClassfiyRecursion(this.treeData, this.isCheckAll);
        this.$refs.tree.setCheckedNodes(this.treeData);
      } else {
        this.selectClassfiyRecursion(this.treeData, this.isCheckAll);
        this.isCheckAllItems = false;
        this.hasChecked = false;
        this.$refs.tree.setCheckedKeys([]);
      }
      this.$set(this.EditionCreateDto, 'functions', this.$refs.tree.getCheckedKeys());
    },
    // 全选时的递归函数：用于全选
    selectAllRecursion(data) {
      for (let i = 0; i < data.length; i += 1) {
        const item = data[i];
        if (item.value === 'False') {
          return 'False';
        }
        if (item.features && item.features.length > 0) {
          this.selectAllRecursion(item.features);
        }
      }
      return 'True';
    },
    // 新增
    saveNew() {
      const that = this;
      this.submitLoading = true;
      this.allCheckedData = [];
      this.getCheckeds(this.toggleTypeList);
      // 获取扩展功能的数据
      CopyData(this.EditionCreateDto_extendDto, this.EditionCreateDto);
      console.log(this.EditionCreateDto);
      this.$refs.EditionCreateDto.validate(valid => {
        if (valid) {
          if (that.hasChecked) {
            // 合并 勾选框的树结构和非勾选框的树结构
            const treeArray = that.sendDefaultList.concat(that.allCheckedData);
            console.log(treeArray);
            that.$emit('insert', that.EditionCreateDto, treeArray);
          } else {
            that.$message({
              // 至少选择一项
              message: translateByCode('rules.selectLeastOne'),
              type: 'warning'
            });
            that.submitLoading = false;
          }
        } else {
          that.submitLoading = false;
          return false;
        }
      });
    },
    // 修改
    saveEdit() {
      const that = this;
      this.submitLoading = true;
      this.allCheckedData = [];
      this.getCheckeds(this.toggleTypeList);
      // 获取扩展功能的数据
      CopyData(this.EditionCreateDto_extendDto, this.EditionCreateDto);
      this.$refs.EditionCreateDto.validate(valid => {
        if (valid) {
          if (that.hasChecked) {
            // 合并 勾选框的树结构和非勾选框的树结构
            const treeArray = that.sendDefaultList.concat(that.allCheckedData);
            console.log(treeArray);
            that.$emit('update', that.EditionCreateDto, treeArray);
          } else {
            that.$message({
              // 至少选择一项
              message: translateByCode('rules.selectLeastOne'),
              type: 'warning'
            });
            that.submitLoading = false;
          }
        } else {
          that.submitLoading = false;
          return false;
        }
      });
    },
    // 获取所有Checked为true的id
    getCheckeds(data) {
      const objForm = {
        name: '',
        value: ''
      };
      for (let i = 0; i < data.length; i += 1) {
        const item = data[i];
        if (item.valueType) {
          objForm.name = item.name;
          objForm.value = item.value;
          this.allCheckedData.push(objForm);
          if (item.value === 'True') {
            this.hasChecked = true;
          }
        }
        if (item.features && item.features.length > 0) {
          this.getCheckeds(item.features);
        }
      }
    },
    openInnerVisible() {
      this.innerVisible = true;
    },
    // 二级弹框的确定
    innerVisibleSaveNew() {
      this.innerVisible = false;
    },
    // 关闭弹框
    innerVisibleClose() {
      this.innerVisible = false;
    },
    // 计算日历选择器的天数
    timeChange(val) {
      var date = (new Date(this.freeDay[1]).getTime() - new Date(this.freeDay[0]).getTime()) / 1000;
      var day = parseInt(date / (24 * 60 * 60) + 1); // 计算整数天数
      this.EditionCreateDto_extendDto.freeDays = day;
    },
    // 免费时长 选择按钮改变
    changeFreeTime(val) {
      switch (val) {
        case '0': // 1天
          this.freeDays.isEnabled = false;
          this.EditionCreateDto_extendDto.freeDays = 1;
          break;
        case '1': // 1个月
          this.freeDays.isEnabled = false;
          // eslint-disable-next-line no-case-declarations
          const endDate = this.getXmonthToday(1);
          this.EditionCreateDto_extendDto.freeDays = this.getDays(this.currentDay, endDate);
          break;
        case 'unlimited': // 不限
          this.freeDays.isEnabled = false;
          this.EditionCreateDto_extendDto.freeDays = 0;
          break;
        case 'free': // 自定义
          this.freeDays.isEnabled = true;
          break;
        default:
          break;
      }
      console.log('freeDays:', this.EditionCreateDto_extendDto.freeDays);
    },
    // 获取一个月后的今天
    getXmonthToday(type) {
      // type 0 是当天 -1 是上个月   1是下个月
      var now = new Date(); // 可以传值调式 now = new Date(2019,2,30); 今天是3月30号
      var year = now.getFullYear(); // getYear()+1900=getFullYear()
      var month = now.getMonth() + 1; // 0-11表示1-12月
      var day = now.getDate(); // 当天日期
      if (parseInt(month) < 10) {
        month = '0' + month;
      }
      if (parseInt(day) < 10) {
        day = '0' + day;
      }
      now = year + '-' + month + '-' + day; // 如果取当月日期可直接 return 返回
      this.currentDay = now; // 当天日期

      var preMonth = parseInt(month) - 1;
      preMonth = preMonth < 10 ? '0' + preMonth : preMonth; // 获取上个月的值
      var nextMonth = parseInt(month) + 1;
      nextMonth = nextMonth < 10 ? '0' + nextMonth : nextMonth; // 获取下个月个月的值

      // eslint-disable-next-line eqeqeq
      if (parseInt(month) == 1 && type == -1) { // 如果是1月份，要上个月 ，则取上一年的12月份
        return (parseInt(year) - 1) + '-12-' + day;
      // eslint-disable-next-line eqeqeq
      } else if (parseInt(month) == 12 && type == 1) { // 如果是12月，要下个月，取下一年的1月
        return (parseInt(year) + 1) + '-01-' + day;
      }

      var preSize = new Date(year, parseInt(month) - 1, 0).getDate(); // 上月总天数
      var nextSize = new Date(year, parseInt(month) + 1, 0).getDate(); // 下月总天数
      // eslint-disable-next-line eqeqeq
      if (preSize < parseInt(day) && type == -1) { // 取上个月，如果上个月总天数小于本月今天，取上个月最后一天
        return year + '-' + preMonth + '-' + preSize;
      // eslint-disable-next-line eqeqeq
      } else if (nextSize < parseInt(day) && type == 1) { // 如果下个月总天数小于本月今天，取下个月最后一天
        return year + '-' + nextMonth + '-' + nextSize;
      }

      // eslint-disable-next-line eqeqeq
      if (type == -1) {
        return year + '-' + preMonth + '-' + day;
      // eslint-disable-next-line eqeqeq
      } else if (type == 1) {
        return year + '-' + nextMonth + '-' + day;
      // eslint-disable-next-line eqeqeq
      } else if (type == 0) {
        return now;
      }
    },
    getDays(dateString1, dateString2) {
      var startDate = Date.parse(dateString1);
      var endDate = Date.parse(dateString2);
      var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
      return days;
    },
    // 授权使用人数 选择按钮改变
    changePeoples(val) {
      this.maxUsers.isEnabled = false;
      switch (val) {
        case '0': // 1人
          this.EditionCreateDto_extendDto.maxUsers = 1;
          break;
        case '1': // 1个月
          this.EditionCreateDto_extendDto.maxUsers = 10;
          break;
        case 'unlimited': // 不限
          this.EditionCreateDto_extendDto.maxUsers = 0;
          break;
        case 'free': // 自定义
          this.maxUsers.isEnabled = true;
          break;
        default:
          break;
      }
    },
    // 允许创建赛事数量 选择按钮改变
    changeGames(val) {
      this.maxEvents.isEnabled = false;
      switch (val) {
        case 'unlimited': // 不限
          this.EditionCreateDto_extendDto.maxEvents = 0;
          break;
        case 'free': // 自定义
          this.maxEvents.isEnabled = true;
          break;
        default:
          break;
      }
    },
    // 允许发布培训数量 选择按钮改变
    changeTrains(val) {
      this.maxTraining.isEnabled = false;
      switch (val) {
        case 'unlimited': // 不限
          this.EditionCreateDto_extendDto.maxTraining = 0;
          break;
        case 'free': // 自定义
          this.maxTraining.isEnabled = true;
          break;
        default:
          break;
      }
    },
    // 允许设置课程数量 选择按钮改变
    changeCurriculum(val) {
      this.maxCourses.isEnabled = false;
      switch (val) {
        case 'unlimited': // 不限
          this.EditionCreateDto_extendDto.maxCourses = 0;
          break;
        case 'free': // 自定义
          this.maxCourses.isEnabled = true;
          break;
        default:
          break;
      }
    },
    // 允许上传资源数量 选择按钮改变
    changeUploads(val) {
      this.maxResources.isEnabled = false;
      switch (val) {
        case 'unlimited': // 不限
          this.EditionCreateDto_extendDto.maxResources = 0;
          break;
        case 'free': // 自定义
          this.maxResources.isEnabled = true;
          break;
        default:
          break;
      }
    }
  }
};
</script>

<style lang="scss">
  .fixHeight{
    height:500px;
  }
  .editVersion .el-scrollbar__bar.is-horizontal{
    display: none;
  }
</style>
<style lang="scss" scoped>
.tree_scroll{
  height:232px;
}
.treeBox{
  position: absolute;
  margin-top: 10px;
  width:100%;
}
.innerVisible_box{
    border-bottom: 1px dashed #c9c9c9;
    padding-bottom: 20px;
}
.innerVisible_title{
    font-size: 14px;
    color: #606266;
    font-weight: bold;
}
.authority-type {
  .el-button {
    margin: 10px 0px 0 0;
    box-sizing: border-box;
  }
}
</style>
